package com.zhiqianbao.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;
import com.zhiqianbao.R;
import com.zhiqianbao.entity.Repay;
import com.zhiqianbao.entity.Result;
import com.zhiqianbao.entity.UserBank;
import com.zhiqianbao.utils.Constants;
import com.zhiqianbao.utils.HttpUtils;
import java.util.HashMap;
import java.util.Map;
import cn.trinea.android.common.util.StringUtils;

/**
 * Created by liang on 2016/1/21.
 */
public class BindBankPhoneConfirmActivity extends BaseActivity implements View.OnClickListener{

    /**
     * 手机验证码
     */
    TextView textViewPayBankPhoneContent;
    /**
     * 确认按钮
     */
    Button buttonConfirm;

    Map<String, Object> dataMap;
    String dataStr;
    Gson gson = new Gson();

    Handler phoneCodeHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RESULT_CANCELED :
                    showShortToast1(Constants.HTTP_ERROR_MESSAGE);
                    break;
                case RESULT_OK :
                    Result<HashMap> phoneCodeResponse = (Result<HashMap>) msg.obj;
                    if(phoneCodeResponse!=null) {
                        if (phoneCodeResponse.getCode().equals(Constants.DEFAULT_SUCCESS_CODE)) {
                            //跳转到支付页面
                            closeWaitDialog();
                            Intent payIntent = new Intent(BindBankPhoneConfirmActivity.this, SelectBankActivity.class);
                            Object robj = dataMap.get("repay");
                            String robjJson = gson.toJson(robj);
                            Repay repay = gson.fromJson(robjJson, Repay.class);
                            payIntent.putExtra("repay", repay);
                            startActivity(payIntent);
                            BindBankPhoneConfirmActivity.this.finish();
                        } else {
                    /*    String from = dataMap.get("from");
                        //如果是从修改银行卡信息过来的，调用修改银行卡信息
                        if ("UpdateBankActivity".equals(from)) {
                            new UpdateBankAsyncTask().execute(dataMap);
                        } else {
                            //绑定银行卡成功，调用第一步保存信息接口
                            new FirstSaveUserInfo().execute(dataMap);
                        }*/

                            showShortToast1(phoneCodeResponse.getMsg());
                            closeWaitDialog();
                        }
                    }
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_bank_phone_confirm);
        init();
        initView();
    }

    private void initView() {
         textViewPayBankPhoneContent=(TextView)findViewById(R.id.textView_pay_bank_phone_content);
         buttonConfirm=(Button)findViewById(R.id.button_confirm);
        dataStr = (String) getIntent().getSerializableExtra("dataStr");
        dataMap = gson.fromJson(dataStr, HashMap.class);
        buttonConfirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
       if(R.id.button_confirm==v.getId()){
                if (StringUtils.isBlank(textViewPayBankPhoneContent.getText().toString())) {
                    showShortToast1("请输入手机验证码");
                    return;
                }
                showWaitDialog();
                //调用绑定验证接口
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        Message message = new Message();
                        Map<String, String> param = new HashMap<>();
                        param.put("userId", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getId() + "" : "");
                        param.put("bankCard", (String) dataMap.get("bankCard"));
                        param.put("validCode", textViewPayBankPhoneContent.getText().toString());
                        param.put("bindToken", (String) dataMap.get("bindToken"));
                        param.put("token", Constants.LOGIN_USER != null ? Constants.LOGIN_USER.getToken() : "");
                        param.put("phoneNo", (String) dataMap.get("bankPhone"));
                        param.put("storableCardNo", (String) dataMap.get("storableCardNo"));
                        param.put("externalRefNumber", (String) dataMap.get("externalRefNumber"));
                        String result = HttpUtils.httpPostString(Constants.API_ROOT + "/payment/bindVerify", param, BindBankPhoneConfirmActivity.this);
                        if (StringUtils.isBlank(result)) {
                            message.what = RESULT_CANCELED;
                        } else {
                            message.what = RESULT_OK;
                            Result<HashMap> phoneCodeResponse = Result.fromJson(result, HashMap.class);
                            message.obj = phoneCodeResponse;
                        }
                        phoneCodeHandler.sendMessage(message);
                    }
                }).start();
        }
    }

    private class UpdateBankAsyncTask extends AsyncTask<Map, Void, Result<UserBank>> {
        @Override
        protected void onPreExecute() {

        }
        @Override
        protected Result<UserBank> doInBackground(Map... params) {
            String result = HttpUtils.httpPostString(Constants.API_ROOT + "/user/changeBankCard", params[0], BindBankPhoneConfirmActivity.this);
            Result<UserBank> resultObject = Result.fromJson(result, UserBank.class);
            return resultObject;
        }
        @Override
        protected void onPostExecute(Result<UserBank> result) {
            if(Constants.DEFAULT_SUCCESS_CODE.equals(result.getCode())) {
                showShortToast1(result.getMsg());
                UserBank userBank = result.getData();
                //更新数据库
                UserBank.deleteAll(UserBank.class);
                userBank.save();
                //数据是使用Intent返回
                Intent intent = new Intent(BindBankPhoneConfirmActivity.this, BankCardInfoActivity.class);
                startActivity(intent);
                //关闭Activity
                BindBankPhoneConfirmActivity.this.finish();
            } else {
                showShortToast1(result.getMsg());
            }
            closeWaitDialog();
        }
    }
}
